<template>
    <div class="cart-page" id="cart-page">
        <!-- 顶部搜索栏background="#F7F9FA"  -->
        <search-sub :isShowCart="false" :isCartPage="true" ref="serach"></search-sub>
        <div class="main">
            <div class="wrap">
                <div class="cart-wrap" v-loading="loadingPage">
                    <h1>购物车</h1>
                    <ol class="cart-table-header">
                        <li class="flex2 first-li">
                            <p>商品信息</p>
                        </li>
                        <li class="flex1" style="opacity: 0">单价</li>
                        <li class="flex1">单价</li>
                        <li class="flex1">数量</li>
                        <li class="flex1">金额</li>
                    </ol>
                    <template v-if="showPage">
                        <div class="cart-table-body" v-if="list.length > 0">
                            <div class="cart-table-th flex" :class="[item.stock_status == 2 || item.goods.status == 20? 'cart-table-th-no' : '']"
                                 v-for="(item, index) in list" :key="index">
                                <div class="goods-info flex flex2">
                                    <template v-if='!isDelFlag'>
                                        <template v-if="item.goods.status == 10">
                                            <div class="cart-select-th flex-center" @click.stop='selectGoods(index)'
                                                 v-if='item.stock_status == 1 || item.stock_status == 3'>
                                                <img src="../../assets/img/cart-checked.png" v-if="item.is_checked" />
                                                <img src="../../assets/img/cart-check.png" v-else />
                                            </div>
                                            <div class="cart-select-th flex-center" v-else>
                                                <p>无库存</p>
                                            </div>
                                        </template>
                                        <template v-else>
                                            <div class="cart-select-th flex-center">
                                                <p>已下架</p>
                                            </div>
                                        </template>
                                    </template>
                                    <template v-else>
                                        <div class="cart-select-th flex-center" @click.stop='selectGoods(index)'>
                                            <img src="../../assets/img/cart-checked.png" v-if="item.is_checked" />
                                            <img src="../../assets/img/cart-check.png" v-else />
                                        </div>
                                    </template>
                                    <div class="goods-img" @click='toGoodsDetial(index,item.goods_id)'>
                                        <base-img :src="item.goods.skuInfo.image ? item.goods.skuInfo.image : item.goods.goods_image"></base-img>
                                    </div>
                                    <div class="goods-name-wrap" @click='toGoodsDetial(index,item.goods_id)'>
                                        <p class="goods-name">
                                            <!-- {{item.id}} -->
                                            {{item.goods.goods_name}}
                                        </p>
                                    </div>
                                </div>
                                <div class="goods-attr flex1" @click='toGoodsDetial(index,item.goods_id)'>
                                    <div class="goods-attr-con">
                                        <p>{{item.goods.skuInfo.spec_value_names}}</p>
                                        <span
                                              v-if='(item.stock_status == 1 || item.stock_status == 3) && item.goods.status == 10'>库存：{{ item.goods.skuInfo.stock_num }}</span>
                                    </div>
                                </div>
                                <span class="goods-price flex1" @click='toGoodsDetial(index,item.goods_id)'>￥{{item.goods.skuInfo.goods_price}}<i v-if='item.goods.skuInfo.goods_unit'>/{{ item.goods.skuInfo.goods_unit }}</i></span>
                                <div class="number-box-wrap flex flex1">
                                    <template v-if="item.goods.status == 10">
                                        <div class="number-box flex" v-if='item.stock_status == 1 || item.stock_status == 3'>
                                            <div class="mins handles flex-center" @click.stop='bindMins(index,item)' :style="{opacity:item.mins_op}">
                                                <img src="../../assets/img/mins.png" />
                                            </div>
                                            <div class="input-box">
                                                <input type="number" v-model="item.goods_num" oninput="value = value.replace(/\s/g, '')"
                                                       @input="getVal($event,item,index)" />
                                            </div>
                                            <div class="plus handles flex-center" @click.stop='bindPlus(index,item)' :style="{opacity:item.plus_op}">
                                                <img src="../../assets/img/plus.png" />
                                            </div>
                                        </div>
                                        <div class="no-stock" v-else>暂无库存</div>
                                    </template>
                                    <div class="no-stock" v-else>下架商品</div>
                                </div>
                                <span class="total-price flex1" :class="[item.stock_status == 2 || item.goods.status == 20 ? 'no-stock-color' : '',
                                ]" @click='toGoodsDetial(index,item.goods_id)'>￥<i>{{ item.total_price }}</i></span>
                            </div>
                        </div>
                        <div class="no-data-wrap" v-else>
                            <no-data text='购物车还是空的,赶紧行动吧!' :noDataImg="noDataImg"></no-data>
                        </div>
                    </template>
                </div>
            </div>
        </div>
        <div class="footer">
            <div class="footer-con">
                <div class="cart-select" @click='selectAll'>
                    <img src="../../assets/img/cart-checked.png" v-if="allChecked" />
                    <img src="../../assets/img/cart-check.png" v-else />
                    <span>全选</span>
                </div>
                <p @click='delHandle'><span>|</span>{{isDelFlag ? '退出管理':'管理'}}</p>
                <div class="total-wrap" v-if='!isDelFlag'>
                    <span>已选商品 {{selectNum}}件</span>
                    <span class="total-text">合计：</span>
                    <em>￥</em>
                    <i>{{ totalPrice }}</i>
                    <el-button class="btn" @click='toSettle'>结算</el-button>
                </div>
                <div class="total-wrap" v-else>
                    <el-button class="btn" @click='delCart'>删除</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import SearchSub from "@/components/SearchSub.vue";
import {
    cartList,
    editCart,
    clearCart,
    getCartTotalPrice,
    orderGoodsCheckOut
} from '../../api/cart';
import {
    userInfo
} from '../../api/base'
import debounce from "@/utils/debounce";
export default {
    components: {
        SearchSub,
    },
    data() {
        return {
            list: [],
            haveStockList: [],
            noStockList: [],
            allChecked: false,
            selectNum: 0,
            totalPrice: 0,
            isDelFlag: false,
            cartErrText: '',
            showToast: false,
            loadingPage: true,
            showPage: false,
            noDataImg: require('../../assets/img/no-cart.png')
        };
    },
    created() {
        this.getList()
    },
    methods: {
        getList(check = '') {
            const that = this;
            cartList({
                check,
            }).then(res => {
                that.loadingPage = false;
                that.showPage = true;
                if (res.code == 0) {
                    res.data.forEach(v => {
                        v.is_checked = false;
                        if (v.goods_num >= v.goods.skuInfo.stock_num) {
                            v.plus_op = 0.4;
                            // v.goods_num = v.goods.skuInfo.stock_num;
                        } else {
                            v.plus_op = 1;
                        }
                        if (v.goods_num <= v.goods.skuInfo.minimum) {
                            v.mins_op = 0.4;
                            // v.goods_num = v.goods.skuInfo.minimum;
                        } else if (v.goods_num == v.goods.skuInfo.stock_num) {
                            if (v.goods_num == v.goods.skuInfo.stock_num == 1) {
                                console.log('添加商品数量和库存相等，且 数量都为1，减号置灰')
                                v.mins_op = 0.4;
                            }
                            v.mins_op = 1;
                        } else {
                            v.mins_op = 1;
                        }
                        const total_price = parseFloat(v.goods_num) * parseFloat(v.goods.skuInfo.goods_price);
                        v.total_price = total_price.toFixed(2);
                    })
                    that.initList(res.data);
                    that.$refs.serach.getCartTotal()
                    // const haveStockList = res.data.filter(v => {
                    //     return v.stock_status == 1 || v.stock_status == 3
                    // })
                    // const noStockList = res.data.filter(v => {
                    //     return v.stock_status == 2
                    // })

                    // that.list = [...haveStockList, ...noStockList];
                    // that.haveStockList = haveStockList
                }
            })
        },
        initList(arr) {
            const that = this;
            const haveStockList = arr.filter(v => {
                return (v.stock_status == 1 || v.stock_status == 3) && v.goods.status != 20
            })
            const noStockList = arr.filter(v => {
                return v.stock_status == 2 || v.goods.status == 20
            })
            that.list = [...haveStockList, ...noStockList];
            that.haveStockList = haveStockList;
            console.log('that.list 更新', that.list)
            console.log('noStockList', noStockList)
            console.log('that.haveStockList 更新', that.haveStockList)
        },
        delHandle() {
            this.isDelFlag = !this.isDelFlag;
            if (this.isDelFlag) {//在管理状态
                console.log('在管理状态')
                if (this.allChecked) {
                    this.list.forEach(v => {
                        v.is_checked = true;
                    })
                }
            } else {
                if (this.allChecked) {
                    this.list.forEach(v => {
                        if (v.stock_status == 1 || v.stock_status == 3) {
                            v.is_checked = true;
                        } else {
                            v.is_checked = false;
                        }
                    })
                    console.log('this.list', this.list)
                    this.selectNum = this.haveStockList.length;
                }
                console.log('退出管理状态')
            }
        },
        //选择商品
        selectGoods(index) {
            let list = this.list,
                allChecked = this.allChecked,
                selectNum = this.selectNum;
            if (list[index].is_checked) {
                list[index].is_checked = false;
                allChecked = false;
                selectNum--;
            } else {
                list[index].is_checked = true;
                if (list[index].stock_status == 1 || list[index].stock_status == 3) {
                    selectNum++;
                }
                if (!this.isDelFlag) {
                    if (selectNum == this.haveStockList.length) {
                        allChecked = true;
                    }
                } else {
                    allChecked = list.every(v => {
                        return v.is_checked === true
                    })
                }
            }
            console.log('allChecked', allChecked)
            console.log('selectNum selectGoods方法', selectNum)
            this.list = list;
            this.allChecked = allChecked;
            this.selectNum = selectNum;
            this.getCartTotalPrice()
        },
        //全选
        selectAll() {
            let selectNum = this.selectNum;
            if (this.allChecked) {
                this.allChecked = false;
                this.list.forEach(v => {
                    v.is_checked = false;
                })
                selectNum = 0;
                this.totalPrice = 0;
            } else {
                this.allChecked = true;
                if (!this.isDelFlag) {
                    this.list.forEach(v => {
                        if (v.stock_status == 1 || v.stock_status == 3) {
                            v.is_checked = true;
                        } else {
                            v.is_checked = false;
                        }
                    })
                    selectNum = this.haveStockList.length;
                } else {
                    this.list.forEach(v => {
                        v.is_checked = true;
                    })
                    selectNum = this.list.length;
                    console.log('在管理状态 全选')
                }
                this.getCartTotalPrice()
            }
            this.selectNum = selectNum;
        },
        getVal(e, item, index) {
            console.log('index', index)
            item.goods_num = '';
            if (e.target.value) {
                item.goods_num = e.target.value;
                if (Number(e.target.value) >= item.goods.skuInfo.stock_num) {
                    item.goods_num = item.goods.skuInfo.stock_num;
                    item.plus_op = 0.4
                    item.mins_op = 1;
                } else if (Number(e.target.value) <= item.goods.skuInfo.minimum) {
                    item.goods_num = item.goods.skuInfo.minimum;
                    item.mins_op = 0.4;
                    item.plus_op = 1;
                } else {
                    item.plus_op = 1;
                    item.mins_op = 1;
                }
                this.editCart(index, item);
            }
        },
        bindPlus(index, item) {
            let list = this.list;
            if (list[index].goods_num >= list[index].goods.skuInfo.stock_num) {
                return;
            }
            list[index].goods_num++;
            list[index].mins_op = '1';
            if (list[index].goods_num >= list[index].goods.skuInfo.stock_num) {
                list[index].goods_num = list[index].goods.skuInfo.stock_num;
                list[index].plus_op = '0.4';
            }
            this.editCart(index, item);
            // this.initList(list)
            // this.list = list;
            // this.editCart(item);
        },
        bindMins(index, item) {
            let list = this.list;
            if (list[index].goods_num <= list[index].goods.skuInfo.minimum) {
                this.$message.error(`最低起卖数量不小于${list[index].goods.skuInfo.minimum}`)
                return;
            }
            list[index].goods_num--;
            list[index].plus_op = '1';
            if (list[index].goods_num <= list[index].goods.skuInfo.minimum) {
                list[index].goods_num = list[index].goods.skuInfo.minimum;
                list[index].mins_op = '0.4';
            }

            this.editCart(index, item);
        },
        clearData() {
            this.selectNum = 0;
            this.totalPrice = 0;
            this.allChecked = false;
            this.getList('check');
        },
        //更新购买数量
        editCart(index, item) {
            const list = this.list;
            editCart({
                goodsId: item.goods_id,
                goodNum: item.goods_num,
                goodsSkuId: item.goods_sku_id
            }).then(res => {
                if (res.code == 0) {
                    const total_price = parseFloat(item.goods_num) * parseFloat(item.goods.skuInfo.goods_price);
                    item.total_price = total_price.toFixed(2);
                    if (item.is_checked) this.getCartTotalPrice();
                    // this.getCartTotalPrice();
                } else if (res.code == 213) {
                    list[index].stock_status = res.data.stock_status;
                    list[index].goods.skuInfo.stock_num = res.data.stock;
                    if (res.data.stock_status == 3) {
                        list[index].goods_num = res.data.stock;
                        list[index].plus_op = '0.4'
                    }
                    console.log('list', list)
                    // this.initList(list)
                    this.clearData()
                }
            })
        },
        //获取购物车总价格
        getCartTotalPrice() {
            let that = this,
                selectGoodsIds = '',
                selectGoodsIdsArr = [];
            const selectGoodsList = this.getSelectGoods();
            selectGoodsList.forEach(v => {
                if (v.stock_status == 1 || v.stock_status == 3) {
                    selectGoodsIdsArr.push(v.id)
                }
            })
            console.log('selectGoodsIdsArr', selectGoodsIdsArr)
            selectGoodsIds = selectGoodsIdsArr.join(',');
            console.log('selectGoodsIds 总价=======', selectGoodsIds)
            getCartTotalPrice({
                cartIds: selectGoodsIds,
            }).then(res => {
                if (res.code == 0) {
                    that.totalPrice = res.totalPrice
                } else if (res.code == 10031) {
                    that.getList();
                    that.allChecked = false;
                    that.selectNum = 0;
                } else {

                }
            })
        },
        //获取选中商品
        getSelectGoods() {
            let selectGoodsList = this.list.filter(v => {
                return v.is_checked == true
            })
            console.log('selectGoodsList', selectGoodsList)
            return selectGoodsList;
        },
        delCart() {
            let that = this,
                list = this.list,
                selectGoodsIds = '';
            const selectGoodsList = this.getSelectGoods();
            var selectGoodsIdsArr = selectGoodsList.map(v => {
                return v.id
            })
            if (selectGoodsIdsArr.length == 0) {
                this.$message.error('没有选中的商品')
                return;
            }
            selectGoodsIds = selectGoodsIdsArr.join(',');
            console.log('selectGoodsIds 删除', selectGoodsIds);
            that.$confirm(`确认要删除这${selectGoodsIdsArr.length}件产品吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                clearCart({
                    cartIds: selectGoodsIds,
                }).then(res => {
                    if (res.code == 0) {
                        that.$message.success(res.msg);
                        const newList = list.filter(v => {
                            return v.is_checked == false
                        })
                        that.list = newList;
                        that.$refs.serach.getCartTotal()
                    }
                })
            }).catch();
        },
        //获取用户信息
        async getUserInfo() {
            let that = this;
            return await new Promise((resolve, reject) => {
                userInfo().then(res => {
                    resolve(res.data)
                }).catch(err => {
                    reject(err)
                })
            })
        },
        async toSettle() {
            let selectGoods = this.getSelectGoods();
            let selectGoodsIdsArr = [];
            selectGoods.forEach(v => {
                if (v.stock_status == 1 || v.stock_status == 3) {
                    selectGoodsIdsArr.push(v.id)
                }
            })
            console.log('selectGoodsIdsArr', selectGoodsIdsArr)
            if (selectGoodsIdsArr.length == 0) {
                this.$message.error('没有选中的商品')
                return;
            }
            const selectGoodsIds = selectGoodsIdsArr.join(',');
            console.log('selectGoodsIds 结算', selectGoodsIds)
            const isAuthRes = await this.getUserInfo();
            console.log('isAuthRes', isAuthRes)
            if (isAuthRes.is_auth != 1) {
                this.$router.push('/user/enterprise_auth')
                return;
            }
            orderGoodsCheckOut({
                cartIds: selectGoodsIds,
                mode: 'cart',
                platform: '2'
            }).then(res => {
                if (res.code == 0) {
                    this.$router.push(`/order/submit_order/${selectGoodsIds}`)
                } else {
                    // this.$message.error(res.msg)
                    // this.getList()
                    this.clearData()
                }
            })
        },
        toGoodsDetial(index,id) {
            let status = this.list[index].goods.status;
            if (status == 20) {
                return;
            }
            const href = this.$router.resolve({
                path: `/goods_detail`,
                query: { goods_id: id },
            }).href;
            window.open(href, "_blank");
            // this.$router.push(`/goods_detail/${id}`)
        }
    }
};
</script>
<style lang="scss" scoped>
::v-deep .el-loading-mask {
    height: calc(100vh - 303px) !important;
}
.cart-page {
    min-height: 100%;
    background: #f7f9fa;
}
.main {
    width: 100%;
    padding-bottom: 120px;
    font-size: 14px;
}
.cart-wrap {
    width: 100%;
    min-height: 912px;
    padding: 0 12px 16px;
    box-sizing: border-box;
    margin: auto;
    background: #fff;
    border-radius: 12px;
    margin-top: 20px;

    h1 {
        font-size: 22px;
        padding-top: 14px;
    }
}

.flex3 {
    flex: 3;
}

.flex2 {
    flex: 2;
}

.flex1 {
    flex: 1;
}
.cart-table-header {
    width: 100%;
    height: 44px;
    padding: 0 12px;
    box-sizing: border-box;
    display: flex;
    align-items: center;

    li {
        text-align: center;
        font-size: 14px;
        font-weight: bold;
    }

    .first-li {
        position: relative;

        .cart-select {
            display: flex;
            align-items: center;
            position: absolute;
            left: -12px;
            top: 0;

            img {
                width: 24px;
                height: 24px;
                margin-right: 5px;
            }
        }
    }
}

.cart-table-body {
    .cart-table-th {
        width: 100%;
        height: 120px;
        padding: 20px 12px;
        box-sizing: border-box;
        background: #f7f9fa;
        border-radius: 8px;
        margin-bottom: 16px;
        font-size: 14px;
        &:last-of-type {
            margin-bottom: 0;
        }
        .cart-select-th {
            width: 38px;
            height: 100%;
            img {
                width: 24px;
                height: 24px;
            }
            p {
                width: 100%;
                height: 24px;
                background: #e1e1e1;
                border-radius: 2px;
                color: #8f8f8f;
                text-align: center;
                line-height: 24px;
                font-size: 10px;
            }
        }
        .goods-img {
            width: 80px;
            height: 80px;
            border-radius: 6px;
            overflow: hidden;
            margin: 0 12px 0 8px;
            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
        }
        .goods-name-wrap {
            flex: 1;
            overflow: hidden;
            .goods-name {
                width: 200px;
                // height: 80px;
                color: #323233;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 2;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }
        .goods-attr {
            color: #9c9c9c;
            .goods-attr-con {
                width: 100%;
                padding: 0 10px;
                box-sizing: border-box;
                span {
                    color: #ff6a01;
                    padding-top: 4px;
                }
            }
        }
        .goods-price {
            color: #9c9c9c;
            text-align: center;
            padding-top: 10px;
        }

        .number-box-wrap {
            position: relative;
            .number-box {
                width: 130px;
                height: 36px;
                border-radius: 6px;
                border: 1px solid #d8d8d8;
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                margin: auto;
                .handles {
                    width: 36px;
                    height: 36px;

                    img {
                        width: 10px;
                        height: 10px;
                    }
                }

                .input-box {
                    width: 58px;
                    height: 36px;

                    input {
                        width: 100%;
                        height: 100%;
                        font-size: 14px;
                        text-align: center;
                        background: transparent;
                    }
                }
            }
        }
        .total-price {
            text-align: center;
            color: #ff6a01;
            font-family: "DIN-BOLD";
            padding-top: 8px;
            i {
                font-size: 16px;
            }
        }
    }
    .cart-table-th-no {
        background: #fff9f8;
    }
    .no-stock {
        width: 100%;
        height: 36px;
        line-height: 36px;
        color: #9c9c9c !important;
        text-align: center;
    }
    .no-stock-color {
        color: #9c9c9c !important;
    }
}
.footer {
    width: 100%;
    height: 103px;
    background: #ffffff;
    box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.16);
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 222;

    .footer-con {
        width: 1180px;
        height: 103px;
        margin: auto;
        display: flex;
        align-items: center;
        padding: 0 12px;
        box-sizing: border-box;
        .cart-select {
            display: flex;
            align-items: center;
            img {
                width: 24px;
                height: 24px;
                margin-right: 5px;
            }
        }
        p {
            span {
                padding: 0 10px;
            }
        }
        .total-wrap {
            flex: 1;
            text-align: right;
            font-weight: bold;
            font-size: 12px;
            em {
                color: #ff4405;
                font-family: "DIN-BOLD";
            }
            i {
                font-size: 22px;
                color: #ff4405;
                font-family: "DIN-BOLD";
            }
            .btn {
                width: 72px;
                height: 36px;
                background: var(--main-color);
                border-radius: 18px;
                margin-left: 24px;
                color: #fff;
                font-weight: bold;
                border: none;
            }
        }
        .total-text {
            padding-left: 20px;
        }
    }
}
.no-data-wrap {
    margin-top: 50px;
}
@media screen and (max-width: 1280px) {
    .footer {
        .footer-con {
            width: 924px;
        }
    }
}
</style>